package webserver;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringReplacement {
    public static void main(String[] args) {
        String originalString = "This is a ${\"api\":\"get_all_sensor_info_and_data\"} and ${placeholder2} example.";

        String replacedString = replacePlaceholders(originalString);
        System.out.println(replacedString);
    }

    public static String replacePlaceholders(String originalString) {
        StringBuilder sb = new StringBuilder();
        Pattern pattern = Pattern.compile("\\$\\{(.+?)}");
        Matcher matcher = pattern.matcher(originalString);

        int lastEnd = 0;
        while (matcher.find()) {
            sb.append("\"").append(originalString, lastEnd, matcher.start()).append("\" + ");
            sb.append("conn.raw(\"")
                .append(matcher.group().substring(1).replaceAll("\"", "\\\\\""))
                .append("\")");
            sb.append(" + ");
            lastEnd = matcher.end();
        }
        if (lastEnd < originalString.length()) {
            sb.append("\"").append(originalString.substring(lastEnd)).append("\"");
        } else {
            sb.delete(sb.length() - 3, sb.length());
        }

        return sb.toString();
    }
}